package com.wuyi.controller;


import com.wuyi.pojo.User;
import com.wuyi.pojo.bo.LoginBO;
import com.wuyi.pojo.bo.RegisterBO;
import com.wuyi.pojo.bo.UserPwdBO;
import com.wuyi.pojo.vo.UsersVO;
import com.wuyi.service.UsersService;
import com.zc.utils.CookieUtils;
import com.zc.utils.JSONResult;
import com.zc.utils.JsonUtils;
import com.zc.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author 曾川
 * @version 1.0.0
 * @ClassName UsersController.java
 * @Description 注册登录Controller
 * @createTime 2021年09月15日 15:32:00
 */
@Api(value = "注册登录",tags = {"用于注册登录的相关接口"})
@RestController
@RequestMapping("users")
public class UsersController {

    final static Logger logger = LoggerFactory.getLogger(UsersController.class);

    public static final String USER_TOKEN = "user_token";

    @Autowired
    private UsersService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @ApiOperation(value = "用户注册（已对接）", notes = "用户注册（已对接）", httpMethod = "POST")
    @PostMapping("/register")
    public JSONResult register(@RequestBody RegisterBO userBO,
                             HttpServletRequest request,
                             HttpServletResponse response) {

        String username = userBO.getUserName();
        String password = userBO.getUserPassword();
        String confirmpassword = userBO.getUserConfirmPassword();

        // 0. 判断用户名和密码必须不为空
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(password) ||
                StringUtils.isBlank(confirmpassword)) {
            return JSONResult.errorMsg("用户名或密码不能为空");
        }
        // 1. 查询用户名是否存在
        boolean isExist = userService.queryUsernameIsExist(username);
        if (isExist) {
            return JSONResult.errorMsg("用户名已经存在");
        }
        // 2. 密码长度不能少于6位
        if (password.length() < 6) {
            return JSONResult.errorMsg("密码长度不能少于6位");
        }
        // 3. 判断两次密码是否一致
        if (!password.equals(confirmpassword)) {
            return JSONResult.errorMsg("两次密码输入不一致");
        }
        // 4. 实现注册
        User userResult = userService.createUser(userBO);
        //敏感信息去除
        userResult = setNullProperty(userResult);

        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(userResult), true);

        logger.info("用户注册Cookies = "+CookieUtils.getCookieValue(request, "user"));
        return JSONResult.ok();

    }

    @ApiOperation(value = "用户登录（已对接）", notes = "用户登录（已对接）", httpMethod = "POST")
    @PostMapping("/login")
    public JSONResult login(@RequestBody LoginBO loginBO,
                            HttpServletRequest request,
                            HttpServletResponse response) throws Exception {

        String userName = loginBO.getUserName();
        String userPassword = loginBO.getUserPassword();

        // 0. 判断用户名和密码必须不为空
        if (StringUtils.isBlank(userName) ||
                StringUtils.isBlank(userPassword)) {
            return JSONResult.errorMsg("用户名或密码不能为空");
        }
        // 1. 实现登录
        User userResult = userService.queryUserForLogin(userName, MD5Utils.getMD5Str(userPassword));
        if (userResult == null) {
            return JSONResult.errorMsg("用户名或密码不正确");
        }
        userResult = setNullProperty(userResult);
        //存入cookie
        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(userResult), true);
        // 生成用户Token，存入redis会话
        String uniqueToken = UUID.randomUUID().toString().trim();
        redisTemplate.opsForValue().set(USER_TOKEN + ":" + userResult.getUserId(), uniqueToken);
        //返回用户信息给前端
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(userResult, usersVO);
        usersVO.setUserUniqueToken(uniqueToken);

        logger.info("用户登录Cookies = "+CookieUtils.getCookieValue(request, "user"));
        logger.info("用户登录Token = " + redisTemplate.opsForValue().get(USER_TOKEN + ":" + userResult.getUserId()));

        return JSONResult.ok(usersVO);

    }

    @ApiOperation(value = "用户登出（已对接）", notes = "用户登出（已对接）", httpMethod = "GET")
    @GetMapping("/logout")
    public JSONResult logout(@RequestParam String userId, HttpServletRequest request, HttpServletResponse response) {
        //清除用户相关信息的Cookie
        CookieUtils.deleteCookie(request, response, "user");
        //分布式会话中需要清除用户数据删除redis的key
        redisTemplate.delete(USER_TOKEN + ":" + userId);

        return JSONResult.ok();

    }




    private User setNullProperty(User userResult) {
        userResult.setUserPassword(null);
        userResult.setCreateTime(null);
        userResult.setUpdateTime(null);
        return userResult;
    }

}
